
package common.packet;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Makes packets out of a DataInputStream.
 *
 * @author xissburg
 */
public class PacketFactory
{
    /**
     * Maps packet codes to packet instances.
     */
    private Map<Packet.Code, Packet> packets;

    public PacketFactory()
    {
        packets = new HashMap<Packet.Code, Packet>();

        Collection<Packet> pCol = new ArrayList<Packet>();
        pCol.add(new Authentication());
        pCol.add(new Authorization());
        pCol.add(new ChatMessage());
        pCol.add(new ClientIn());
        pCol.add(new ClientOut());
        pCol.add(new ClientInfo());
        pCol.add(new Input());
        pCol.add(new Error());
        pCol.add(new GameState());
        pCol.add(new WorldState());
        pCol.add(new OK());

        for(Packet p: pCol)
            packets.put(p.getCode(), p);
    }

    public Packet readPacket(DataInputStream in) throws IOException,
                                                        IllegalArgumentException
    {
        Packet.Code code = Packet.Code.valueOf(in.readUTF());

        Packet packet = packets.get(code);

        if(packet != null)
        {
            packet.read(in);
            packet = packet.copy();
        }
        else
            packet = new PacketWithCode(code);

        return packet;
    }
}
